﻿package cn.poco.xw.activity.init;

import java.util.List;

import cn.poco.adapter.SwitchCityListAdapter;
import cn.poco.bean.City;
import cn.poco.constants.Constants;
import cn.poco.service.impl.CityImpl;
import cn.poco.service.impl.SearchImpl;
import cn.poco.util.GpsLocationUtil;


import cn.poco.xw.R;
import cn.poco.xw.activity.search.thread.SearchUtil;
import cn.poco.xw.activity.tab.TabActivity;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class SwitchCityActivity extends Activity {
	
	/** constants **/
	private final static String TAG = "SwitchCityActivity";
	private final static int CITY_SUCCESS = 1;
	
	private ListView cityListView;
	private static List<City> listCity = null;
	private SwitchCityListAdapter adapter;
	private LinearLayout progressbar;
	
	/** GPS 设置 **/
	private City city; //保存GPS定位城市信息
	private Handler tHandler = null;
	
	/** 连接错误显示 **/
	private LinearLayout error;
	private Boolean allCity = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.switch_city);
		/**
		 * <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
              <include layout="@layout/error"/>
              <include layout="@layout/progressbar"/>
              <include layout="@layout/listview"/>	  
            </FrameLayout>
		 * 包括三个布局：错误界面、进度条、列表
		 * 
		 * */
		
		allCity = false;
		cityListView = (ListView)findViewById(R.id.listview); //cityListView是用来显示城市的名称
		progressbar = (LinearLayout)findViewById(R.id.progressbar);
		error = (LinearLayout)findViewById(R.id.error);
		Button tautology = (Button)findViewById(R.id.tautology);
		Button setBtn = (Button)findViewById(R.id.setnet);
		
		
		//setBtn  按钮   加入监听  :本程序跳转到设置的无线和网络
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});
		
		
	   //切换城市界面：列表事件处理
		cityListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					final long id) {
				if(position!=0 && listCity.get(position-1).getKey().equals("000000")){
					
					//SwitchCityListAdapter adapter
					
						adapter.setAllCity(true);
						listCity.remove(position-1);
					adapter.notifyDataSetChanged();
					
					
				}else if(id==-1){
					
				}else{
						
					//保存城市参数到SharedPreferences
					SharedPreferences preferences  = getSharedPreferences(Constants.CITY_CODE, Context.MODE_PRIVATE);
					SharedPreferences.Editor editor = preferences.edit();
					editor.putLong(Constants.CITY_CODE, id);
					
					int pos = 0;
					if(position>0){
						pos=position-1;
					}
					editor.putString(Constants.CITY_NAME, listCity.get(pos).getName());
					editor.commit();//提交
					
					
				   //新开一线程
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								SearchUtil.getArea(SwitchCityActivity.this, String.valueOf(id));
								SearchImpl search = new SearchImpl();
								search.getDishs(String.valueOf(id), "dish",SwitchCityActivity.this);
							} catch (Exception e) {
								Log.e(TAG, e.toString());
								e.printStackTrace();
							}
						}
					}).start();
					
					
					
					
					//启动主界面：切换城市界面--->主界面TabActivity
					Intent tabInent  = new Intent(SwitchCityActivity.this,TabActivity.class);
					Bundle bundle = new Bundle();
					//附带两个信息发送到--->[主界面TabActivity]：CITY_CODE  CITY_NAME
					bundle.putLong(Constants.CITY_CODE, id);
					bundle.putString(Constants.CITY_NAME, listCity.get(pos).getName());
					tabInent.putExtras(bundle);
					startActivity(tabInent);
					SwitchCityActivity.this.finish();
				
				}
				
				
			}
		});
		
		
		
		//重试按钮
		tautology.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressbar.setVisibility(View.VISIBLE);
				error.setVisibility(View.GONE);//隐藏错误提示界面
				
				//1.获取城市列表   post方法(重试)
				tHandler.post(new GetCity());
			}
		});
		
		//新开一线程，用于调用Handler类来获取城市列表
	    HandlerThread handlerThread = new HandlerThread("myHandlerThread");
        handlerThread.start();
        tHandler = new Handler(handlerThread.getLooper());
		
        //1.获取城市列表   post方法
        tHandler.post(new GetCity());
	
	
	}//************         onCreat事件结束                     ******************

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		//menu.removeItem(R.id.recentlyviewed);
		menu.removeItem(R.id.switchcity);
		return super.onPrepareOptionsMenu(menu);
	}
	
	
	
	//更新GPS信息  线程类
	private final class UpdateGpsInfo implements Runnable{
		private Location location;
		private Double lat;
		private Double lon;
		
		
		//带两参数的构造函数
		public UpdateGpsInfo(Double lat,Double lon) {
			this.lat = lat;
			this.lon = lon;
		}
		
		
		@Override
		public void run() {
			CityImpl icity = new CityImpl();
			try {
			 if(location!=null){
				    //通过GPS切换城市<-------传入经纬度
					city = icity.switchCitybyGps(location.getLatitude(), location.getLongitude());
				}else{
					//location为空时，通过原来的值获取城市信息
					city = icity.switchCitybyGps(lat,lon);
				}
			} catch (Exception e) {
				Log.e(TAG, e.toString());
				e.printStackTrace();
			}
			
			
			Message msg = new Message();
			msg.what = Constants.GPS_UPDATE;
			//发送要处理的信号，GPS更新了
			handler.sendMessage(msg);	//handleMessage(Message msg)会根据信号做出相应的处里动作
		}
	}
	
	

	@Override
	protected void onPause() {
		super.onPause();
		GpsLocationUtil.getInstance(SwitchCityActivity.this).unRequestListener();
	}
	
	


	@Override
	protected void onResume() {
		super.onResume();
/*		//启动GPS监听
		GpsLocationUtil gpsUtil =GpsLocationUtil.getInstance(SwitchCityActivity.this);
		gpsUtil.getLocation(handler);*/
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		GpsLocationUtil gpsUtil =GpsLocationUtil.getInstance(SwitchCityActivity.this);
		gpsUtil.getLocation(handler);
	}


	//获取城市方法
	private final class GetCity implements Runnable{
		@Override
		public void run() {
			
			//城市接口实现类  对象实例
			CityImpl iCity = new CityImpl();
			
			try {
				listCity = iCity.switchCity(SwitchCityActivity.this);
			} catch (Exception e) {
				System.out.println("异常－－－－－－－－－－－－");
				handler.sendEmptyMessage(Constants.CONN_ERROR);
				Log.e(TAG, e.toString());
				e.printStackTrace();
			}
			if(listCity!=null){
				Message msg = new Message();
				msg.what=CITY_SUCCESS;
				handler.sendMessage(msg);
			}	
		}	
	}
	
	
	private Handler handler = new Handler(){

		//更新UI回调方法
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			//根据msg.what的内容作出相应的处理动作
			switch (msg.what) {
			
		    // 获取城市成功     更新UI
			case CITY_SUCCESS: //数值为1
				progressbar.setVisibility(View.GONE);//隐藏进度条的图视
				
				if(allCity==false){//如果不是全部的城市信息，加入"更多的"
					City more = new City();
					more.setKey("000000");
					more.setName("更多");
					listCity.add(4,more);
				}
				
				
				
				/**
				 * SwitchCityListAdapter类，用来给ListView填充数据
				 * //构造函数
	          public SwitchCityListAdapter(Context context,List<City> listCity,String []gpsInfo,Boolean allCity)
				 * 
				 * */
				adapter = new SwitchCityListAdapter(SwitchCityActivity.this, listCity,new String[]{"GPS定位中..."},allCity);
				cityListView.setAdapter(adapter);
				cityListView.setVisibility(View.VISIBLE);
				
				//启动GPS监听
				GpsLocationUtil gpsUtil =GpsLocationUtil.getInstance(SwitchCityActivity.this);
				gpsUtil.getLocation(handler);
				break;
				
				
			//GPS更新
			case Constants.GPS_UPDATE:
				String [] cityInto = null ;
				
				//城市名不为空
				if(city.getName()!=null && city.getName()!=""){
					
					//实例化数组   并为数组赋值
					cityInto= new String[10];
					cityInto[0] = city.getName();
					cityInto[1] = city.getKey();
					
					//将城市信息保存到SharedPreferences
					SharedPreferences preferences  = getSharedPreferences(Constants.GPS_CITY_CODE, 
							Context.MODE_PRIVATE);
					SharedPreferences.Editor editor = preferences.edit();
					editor.putString(Constants.CITY_CODE, cityInto[1]);
					editor.commit();
					
					
				//城市名为空	
				}else{
					cityInto = new String[]{"-1"};//给cityInto赋值"-1",表示没有任何城市信息
				}
				
				
				
				//将城市信息的数组赋给  adapter.cityInfo
				adapter.cityInfo =cityInto;
				adapter.notifyDataSetChanged();//通知数据设置改变
				
				
				//将城市信息的数组清空
				cityInto = null;
				break;
			
				
			//GPS位置改变    重新获取城市信息
			case Constants.GPS_LOCATION_CHANGE:
				GpsLocationUtil.getInstance(SwitchCityActivity.this).unRequestListener();
				Bundle bundle = msg.getData();
				Double lat = bundle.getDouble(Constants.GPS_LAT);
				Double lon = bundle.getDouble(Constants.GPS_LONG);
				//获取城市列表
				tHandler.post(new UpdateGpsInfo(lat,lon));
				break;
				
				
			//GPS没有打开，提示是否开启GPS
			case Constants.NO_GPS:
				new AlertDialog.Builder(SwitchCityActivity.this)
				.setTitle("错误")
				.setMessage("没有打开GPS设置,无法获取您的位置信息，现在开启?")
				.setNegativeButton("取消", null)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
						
					}
				}).show();
				break;
				
				
			//连接错误
			case Constants.CONN_ERROR:
				System.out.println("错误 －－－－－－－－－－－－");
				progressbar.setVisibility(View.GONE);
				error.setVisibility(View.VISIBLE);
				
				break;
				
			}
			
		}
		
	};
	
}
